package com.code.generator.code.impl;

import com.code.generator.context.velocity.VelocityGeneratorContext;
import com.code.config.OutParentDirEnum;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public abstract class AbstractVelocityGenerator
        extends AbstractGenerator<VelocityGeneratorContext> {

    @Override
    public void generate(VelocityGeneratorContext context) throws IOException {
        Template template = Velocity.getTemplate(this.getTemplateName(context));
        String parent = OutParentDirEnum.getTypeByTemplate(template.getName());
        Writer writer = this.getWriter(context, parent);
        template.merge(context, writer);
        writer.close();
    }

    protected Writer getWriter(VelocityGeneratorContext context, String parent) throws IOException {
        return new FileWriter(this.buildFile(context, parent,
                this.getPackageName(context), this.getFileName(context)));
    }


    protected abstract String getTemplateName(VelocityGeneratorContext context);

    protected abstract String getPackageName(VelocityGeneratorContext context);

    protected abstract String getFileName(VelocityGeneratorContext context);
}
